<?php
/** 
 * @package AMFramework
 * @subpackage Core_MVC
 * @author Marcu Alexandru
 * @version 1.0 $Build 305b  
 */
defined('_INDEX') or die('Restricted');

class Amfw_Loader extends Amfw_Object {
	protected $_controller;
	//protected $_router;
	
	public function __construct() 
	{
		$this->_initDocument();
		$this->__initAll(array('Document')); // TODO: Moved from the last to the first position so the init methods load 
											//before the controller
		//$this->_createRouter();
		$this->_createController();
		$this->initController();

	}
	
	// Protected ==============================================================
	protected function _createController() 
	{
		if(is_subclass_of($this,'Amfw_Loader')):

			global $framework;
			//global $debug;
				
			$info = $this->mirror($this); // Gets information of the current class (name, prefix, etc)

			$controller_request = Amfw_Request::getv('controller',null);
			
			if(is_string($controller_request)) {
				//$debug->logWrite('Controller will be loaded from request: '.ucfirst($controller_request));
				$controller = $info['prefix'].'_Controller_'.ucfirst($controller_request);
			}
			else 
			{
				$apps = $framework->getConfig('applications');

				foreach($apps as $app) {
					if($app->prefix == $info['prefix']){
						//$debug->logWrite('Controller will be loaded from default controller setting');
						$controller = ucfirst($app->prefix) . '_Controller_' . ucfirst($app->controller);
						break;
					}
				}//~!foreach
			}//~!else
			$this->_controller = new $controller();
		endif;
	}
	
	protected function initController() 
	{
		// Metoda ce poate fi suprascrisa in loaderul
		// aplicatiei daca se doreste pornirea controllerului
		// intr-o alta maniera.
		if(isset( $this->_controller )):
			$this->_controller->init(true);
			return true;
		else: 
			trigger_error("Error <b>loading the front controller</b>.<br/>", E_USER_ERROR);
			return false;
		endif;
	}
	
	/* protected function _createRouter() 
	 { 	// Rutarea se face inainte de controller
	 	if(is_subclass_of($this,'Amfw_Loader')):
	 		global $debug;

			$info = $this->mirror($this);
			$router = ucfirst( $info['prefix'] ) . '_' . 'Router';

			if(@class_exists($router,true)) {
				$debug->logWrite('Routing class: '.$router.' will be loaded');
				$this->_router = new $router();
			} 
			else 
			{
				$debug->logWrite('Routing class: '.$router.' not found, using the default router',AMFW_JOURNAL);
				$this->_router = new Amfw_Router_Default();
			}
		endif;
	} */
	
	public function _initDocument()
	{
		if(is_subclass_of($this,'Amfw_loader')):
		Amfw_Debug::toJournal('_initDocument()');
			global $framework;
			
			$app = Amfw_Application::_();

			$doc = $framework->getDocument();
			$doc->setTitle(@$app->information['title']);
			$doc->addMeta('keywords', @$app->information['keywords']);
			$doc->addMeta('description', @$app->information['description']);
			$doc->setLanguage(@$app->information['language']);
			
			$tmpl = Amfw_Template::getInstance();
			if(!empty($app->information['template'])) {
				$tmpl->setName($app->information['template']); // setam template-ul implicit
			}
			//TODO: E mai mult o setare a templateului, nu stiu cat de relevanta e aici
			$doc->setDoctype(@$app->information['doctype']);

			//TODO: Utile poate doar pentru module, deci de gandit la feature
			if(!empty($app->scripts)) {
				foreach ($app->scripts as $script) {
					$doc->addScript($script);
				}
			}
			if(!empty($app->stylesheets)) {
				foreach ($app->stylesheets as $stylesheet) {
					$doc->addStylesheet($stylesheet);
				}
			}
			return;
		endif;
	}
	
	public function __destruct()
	{
		// Idea: Template display (si probabil si parse) ar trebui sa se dea cat mai tarziu;
		$tmpl = Amfw_Template::getInstance();
		echo $tmpl->display(); 
	/*	TODO: Activarea cacheului in functie de profil de debugging, stocarea informatiilor, etc
		// Caching
		// Set a id for this cache
		$id = Amfw_Request::getv('task',null); //cel mai probabil ar trebui sa fie URI-ul
//		var_dump($id);
		
		// Set a few options
		$options = array(
		    'cacheDir' => BASE_PATH.DS.'Cache'  ,
		    'lifeTime' => 3600
		);
		//var_dump($options['cacheDir']);
		$cache = new PEAR_Cache($options);
		if( $data = $cache->get($id) ) {
			echo $data;
		} else {
			$cache->save($tmpl->display());
		}
		*/
	}
}